package com.kobeliu.entity;

import java.util.Arrays;

public class Demo_18_No16 {

    public static void main(String[] args) {
//[-1,2,1,-4]
//1
        int[] nums = {1,1,-1,-1,3};
        int target = -1;
        System.out.println(threeSumClosest(nums,target));

    }

    public static int threeSumClosest(int[] nums, int target) {
        int sum = 0;
        int len = nums.length;
        if(len<3){
            return sum;
        }
        sum=nums[0]+nums[1]+nums[2];
        Arrays.sort(nums);//将数组排序，默认是归并
        for (int i = 0; i < len-2; i++) {
            int L = i+1;
            int R = len-1;
            while(L!=R){
                int n = nums[i]+nums[L]+nums[R];
                if(Math.abs(sum-target)>Math.abs(n-target)){
                    sum = n;
                }
                if(target-n==0){
                    return target;
                }else if(target>n){
                    L++;
                }else{
                    R--;
                }
            }

        }
        return sum;
    }
}
